package cn.wolfcode.luowowo.interceptor;


import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆拦截
 */
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            //将handler强转为HandlerMethod，只拦截动态请求的方法，防止后期如果添加静态资源，静态请求被拦截
            HandlerMethod hm = (HandlerMethod) handler;
            //方法贴有这个注解，就判断用户是否已经登录过
            if (hm.hasMethodAnnotation(RequireLogin.class)) {
                //拿到请求头只给你的令牌
                String token = request.getHeader("token");
                //通过token去查询Redis缓存中是否已经存在了已经登录的用户信息
                UserInfo u = userInfoRedisService.getUserInfoByToken(token);
                if (u == null) {
                    //不放行之前，给用户提示点信息让它去登录（请求是json，响应的也要是json）
                    response.getWriter().print(JSON.toJSONString(JsonResult.noLogin()));
                    //查无此人，不放行
                    return false;
                }
            }
        }
        //没贴自定义注解或其他静态请求，直接放行
        return true;
    }
}
